package mysql

import (
	"fmt"
	"short-video-manager/appconfig"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var err error
var DB *gorm.DB

func Init() {
	m := appconfig.ConfigData.Mysql
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.User, m.Password, m.Host, m.Port, m.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败")
	}
	fmt.Println("数据库连接成功")
	err = DB.AutoMigrate(&UserInfo{}, &VideoInfo{}, &CommentInfo{}, &CollectionInfo{}, &TopicInfo{})
	if err != nil {
		panic("数据表迁移失败")
	}
	fmt.Println("数据表迁移成功")
}
func Paginate(page, size int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}
		switch {
		case size > 100:
			size = 100
		case size <= 0:
			size = 10
		}

		offset := (page - 1) * size
		return db.Offset(offset).Limit(size)
	}
}
